jQuery.cleditor.defaultOptions.width = 587;
jQuery.cleditor.defaultOptions.height = 200;
jQuery.cleditor.defaultOptions.controls = "bold italic underline";
var loading = false;

jQuery(document).ready(function() {
	// bind edit button for goal entry
	jQuery(".edit_entry_pop").click(function() {
		entryId = jQuery(this).attr("rel");
		showEditor(entryId);
	});
});

function showEditor(entryId) {
	jQuery("#entry_holder_" + entryId).hide().fadeOut('slow');
	html = jQuery("div[id=edit_entry_holder]").html();
	$editPart = jQuery("div[id=edit_entry_holder_" + entryId + "]"); 
	
	GoalEntryManager.getEntry(entryId, {
		callback: function(entry) {
			title = entry.title;
			body = entry.body;
			imgURL = entry.imgURL;
			html = html.replace(/@entryId@/g, entryId);
			html = html.replace(/@title@/g, title);
			html = html.replace(/@body@/g, body);
			html = html.replace(/@imgURL@/g, imgURL);
			$editPart.html(html);
			jQuery("textarea[name=body]", $editPart).cleditor();
			
			bindEntryUploadForm(entryId);
			bindEntryForm(entryId);
		},
		exceptionHandler: function(message, exception) {			
			iAlert("Hệ thống đang bị lỗi");
			return;
	    }
	});
}

function removeEditor(entryId) {
	jQuery("#edit_entry_holder_" + entryId).empty();
	jQuery("#entry_holder_" + entryId).fadeIn('slow');
}

function bindEntryUploadForm(entryId) {
	rel = "edit_entry_" + entryId;
	jQuery("form[id^='upload_form_'][rel=" + rel + "]").ajaxForm({
		url : '/fileupload/file',
		type : 'post',
		dataType : 'xml',		
		beforeSubmit : validateImageUploadEntry,
		success : updateImagePathEntry
	});
	
	jQuery("a#uploadAvatarSubmitButton[rel=" + rel + "]").unbind("click").click(function(){
		if(loading == true){
			return false;
		}
		loading = true;
		jQuery("form[id^='upload_form_'][rel=" + rel + "]").submit();
		return false;
	});
}

function bindEntryForm(entryId) {
	rel = "edit_entry_" + entryId;
	jQuery("a[id=save_entry_" + entryId + "]").unbind('click').click(function() {
		$form = jQuery("form[id^='entry_form_'][rel=" + rel + "]");
		id = jQuery("input[name=entryId]", $form).val();
		title = jQuery("input[name=title]", $form).val();
		body = jQuery("[name=body]", $form).val();
		imgURL = jQuery("input[name=imgURL]", $form).val();
		
		if (validateEntry(title, body)) {
			saveEntry(id, title, body, imgURL);
		} else {
			iAlert("Hệ thống đang bị lỗi");
		}
		
		return false;
	});
	
	jQuery("a[id^='delete_entry_']").unbind('click').click(function() {
		removeEditor(entryId);
		return false;
	});
}

function saveEntry(id, title, body, imgURL) {
	var entryDTO = {
		id: id,
		title: title,
		body: body,
		imgURL: imgURL
	};
	GoalEntryManager.saveEntry(entryDTO, {
		callback: function(result){
			if(result == 1){
				removeEditor(id);
				if (imgURL.length > 0) {
					if (jQuery("#entry_holder_" + id + " .entryDashboard img").length > 0) {
						jQuery("#entry_holder_" + id + " .entryDashboard").attr("href", imgURL);
						jQuery("#entry_holder_" + id + " .entryDashboard img").attr("src", imgURL);
						jQuery("#entry_holder_" + id + " div.ppy-stage").css("background-image", "url(" + imgURL + ")");
					} else {
						html = "<div class='ppy' id='ppy1'><ul class='ppy-imglist'><li><a href='" + imgURL + "' class='entryDashboard'><img src='" + imgURL + "' /></a></li></ul><div class='ppy-outer'><div class='ppy-stage'><div class='ppy-nav'><a class='ppy-prev' title='Hình trước'>Hình trước</a><a class='ppy-switch-enlarge' title='Phóng to'>Phóng to</a><a class='ppy-switch-compact' title='Đóng'>Đóng</a><a class='ppy-next' title='Hình sau'>Hình sau</a></div></div></div></div>";
						jQuery("#entry_holder_" + id + " .infogoal").prepend(html);
						jQuery("#entry_holder_" + id + " .ppy").popeye();
					}
				}
				jQuery("#entry_holder_" + id + " h1 a").html(title);
				jQuery("#entry_holder_" + id + " .text[rel=readmore]").html(body);
			} else {				
				iAlert("Hệ thống đang bị lỗi");
			}				
		}, 
		exceptionHandler: function(message, exception) {			
			iAlert("Hệ thống đang bị lỗi");
	    }
	});
}

function updateImagePathEntry(responseText, statusText, xhr, $form) {
	var image = jQuery('image', responseText).text();
	rel = $form.attr("rel");
	jQuery("input[name='imgURL'][rel=" + rel + "]").val(image);
	jQuery("img[id^='preview_'][rel=" + rel + "]").attr("src", image).hide().fadeIn('slow');
	if (image != null && image != "") {
		jQuery("img[id^='preview_'][rel=" + rel + "]").parent().show();
	} else {
		jQuery("img[id^='preview_'][rel=" + rel + "]").parent().hide();
	}
	
	$form.find(".txtFileNameEntry").iUnblock();
	loading = false;
	var $progressBar = $form.next('#progressBar');
	$progressBar.find('#progressBarBoxContent').css('width', '350px');
	$progressBar.hide("slow");
}

function validateImageUploadEntry(formData, jqForm, options) {
	var form = jqForm[0];
	if (form.image.value) {
		jQuery(form).find(".txtFileNameEntry").iBlock({});
		return true;
	}
	
	iAlert("Bạn chưa chọn hình ảnh để upload");
	return false;
}

function validateEntry(title, body) {
	if (!title) {
		iAlert("Bạn chưa nhập tiêu để cho bài viết");
		return false;
	}
	if (!body) {
		iAlert("Bạn chưa nhập nội dung bài viết");
		return false;
	}
	
	return true;
}
